package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.EssayCourseQuestionBank;
import com.wzcl.app.dao.repository.EssayCourseQuestionBankRepository;
import com.wzcl.app.model.common.MyPage;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.model.dto.EssayCourseQuestionBankDto;
import com.wzcl.app.service.EssayCourseQuestionBankService;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author beingven
 * @Description TODO
 * @createTime 2020年12月25日 16:09:00
 */
@Service
public class EssayCourseQuestionBankServiceImpl implements EssayCourseQuestionBankService {
    @Resource
    private EssayCourseQuestionBankRepository essayCourseQuestionBankRepository;

    @Override
    public List<EssayCourseQuestionBank> importQuestionBank(List<EssayCourseQuestionBank> questionBanks) {
        return essayCourseQuestionBankRepository.saveAll(questionBanks);
    }

    @Override
    public MyPage<EssayCourseQuestionBank> retrieveAllByPage(EssayCourseQuestionBankDto questionBankDto) {
        Page all = essayCourseQuestionBankRepository.findAll(getSpecification(questionBankDto), questionBankDto.getPageable());
        return new MyPage<>(all);
    }

    @Override
    @Transactional
    public RVO deleteByIds(List<Integer> ids) {
        Iterator<Integer> iterator = ids.iterator();
        while (iterator.hasNext()) {
            essayCourseQuestionBankRepository.deleteById(iterator.next());
        }
        return RVO.success("删除成功");
    }

    @Override
    @Transactional
    public RVO deleteAll() {
        essayCourseQuestionBankRepository.deleteAll();
        return RVO.success("一键删除成功");
    }

    @Override
    public List<EssayCourseQuestionBank> retrieveAll() {
        List<EssayCourseQuestionBank> all = essayCourseQuestionBankRepository.findAll();
        return all;
    }

    //分页查询题库条件过滤
    public Specification<EssayCourseQuestionBank> getSpecification(EssayCourseQuestionBankDto questionBankDto){
        return (Specification<EssayCourseQuestionBank>) (root, criteriaQuery, criteriaBuilder) -> {
            ArrayList<Predicate> list = new ArrayList<>();
            //条件过滤
            if (questionBankDto.getQuestionType() != null){
                //按类型筛选
                list.add(criteriaBuilder.equal(root.get("questionType"), questionBankDto.getQuestionType()));
            }
            if (questionBankDto.getQuestion() != null){
                list.add((criteriaBuilder.like(root.get(""), "%"+ questionBankDto.getQuestion() +"%")));
            }
            //将两个查询条件联合起来之后返回Predicate对象
            return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
        };
    }
}
